<!--
 @Author: libing/makeup1122
 @Email: makeup1123@163.com
 @Date: "2020-02-29 15:38:02"
-->
<template>
  <v-data-table
  dense
  :loading="tableLoading"
  :headers="tableHeaders"
  :items="tableItems"
  calculate-widths
  must-sort
  :server-items-length="tableItemsTotal"
  :footer-props="{
      showFirstLastPage: true,
      showCurrentPage: true,
      itemsPerPageOptions: [5, 20, 30, 50]
  }"
  :options.sync="tableOptions">
    <template v-slot:top>
      <v-toolbar flat class="mb-1">
        <v-text-field
        color="secondary"
        solo-inverted
        v-model="tableSearch"
        append-icon="search"
        @change="fetchData"
        dense
        clearable
        flat
        hide-details
        label="搜索"/>
        <v-dialog v-model="dialog">
          <template v-slot:activator="{ on }">
            <v-btn v-on="on" color="primary" class="mx-5">
              <v-icon>add</v-icon>
              发送消息
            </v-btn>
          </template>
          <v-form ref="dialogForm">
            <v-card tile class="pa-5 ma-0">
              <v-tabs v-model="tabIndex">
                <v-tab v-for="(item,i) in typeArrayText" :key="i">{{item}}</v-tab>
                <v-tab-item>
                  Artical
                </v-tab-item>
                <v-tab-item>
                  <v-textarea
                  v-model="formData.content"
                  counter
                  placeholder="请输入要群发的文字内容"></v-textarea>
                </v-tab-item>
                <v-tab-item>
                  <v-lazy>
                    <MaterialSelect type="image" label="图片素材" :thumb_media_id.sync="formData.media_id"/>
                  </v-lazy>
                </v-tab-item>
                <v-tab-item>
                  <v-lazy>
                    <MaterialSelect type="video" label="视频素材" :thumb_media_id.sync="formData.media_id"/>
                  </v-lazy>
                </v-tab-item>
                <v-tab-item>
                  <v-lazy>
                    <MaterialSelect type="audio" label="音频素材" :thumb_media_id.sync="formData.media_id"/>
                  </v-lazy>
                </v-tab-item>
              </v-tabs>
              <v-radio-group v-model="formData.scope" row dense mandatory>
                <v-radio label="群发所有用户" value="all"></v-radio>
                <v-radio label="按标签群发" value="tags"></v-radio>
                <v-radio label="发给指定用户" value="openid"></v-radio>
              </v-radio-group>
              <TagsSelect v-if="formData.scope === 'tags'" v-model="formData.touser"/>
              <MemberSelect multiple v-if="formData.scope === 'openid'" v-model="formData.touser"/>
              <v-checkbox label="立即发送" v-model="formData.send_right_now" true-value="1" false-value="0"></v-checkbox>
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn class="mr-5" @click="sumbitHandle" color="primary" :loading="btnLoading"><v-icon>save</v-icon>提交</v-btn>
                <MaterialPreview v-bind="formData"/>
                <v-btn class="ml-5" @click="dialog = false" :loading="btnLoading"><v-icon>close</v-icon>取消</v-btn>
              </v-card-actions>
            </v-card>
          </v-form>
        </v-dialog>
      </v-toolbar>
    </template>
    <template v-slot:item.type="{ item }">
      {{typeArrayText[typeArray.indexOf(item.type)]}}
    </template>
    <template v-slot:item.touser="{ item }">
      <span v-if="item.scope === 'all'" class="primary--text">所有人</span>
      <span v-else-if="item.scope === 'tags'" class="secondary--text">标签: {{item.touser.scalar}}</span>
      <span v-else class="accent--text">用户：{{item.touser}}</span>
    </template>
    <template v-slot:item.status="{ item }">
      <v-chip small v-if="item.status === 'save'">已保存</v-chip>
      <v-chip small v-else-if="item.status === 'send'" color="success">已发送</v-chip>
      <v-chip small v-else-if="item.status === 'error'" color="error">错误</v-chip>
      <v-chip small v-else color="warning">{{item.status}}</v-chip>
    </template>
    <template v-slot:item.actions="{ item }">
      <MaterialPreview v-bind="item" v-if="item.status === 'save'" text/>
      <v-btn v-if="item.status === 'save'" @click="itemSendHandle(item)" color="primary" text small><v-icon>send</v-icon>发送</v-btn>
      <v-btn :disabled="(item.status === 'send' && (item.type !== 'artical' || item.type !== 'video'))" @click="itemDeleteHandle(item)" color="warning" text small><v-icon>delete</v-icon>删除</v-btn>
    </template>
    <!-- <template v-slot:footer>
      <v-divider></v-divider>
      <v-row class="mt-5" align="center" justify="center">
        <v-col class="text-sm-right"><span class="grey--text">共<b>{{tableItemsTotal}}</b>条</span></v-col>
        <v-col><v-pagination v-model="tableOptions.page" :length="tablePageLength" ></v-pagination></v-col>
        <v-col class="text-sm-left">
        <span class="grey--text">每页个数</span>
          <v-menu offset-y>
            <template v-slot:activator="{ on }">
              <v-btn dark text color="primary" class="ml-0" v-on="on">
                {{ tableOptions.itemsPerPage }}
                <v-icon>keyboard_arrow_down</v-icon>
              </v-btn>
            </template>
            <v-list>
              <v-list-item v-for="(number, index) in [10, 20, 30, 50]" :key="index" @click="tableOptions.itemsPerPage = number">
                <v-list-item-title>{{ number }}</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
        </v-col>
      </v-row>
    </template> -->
  </v-data-table>
</template>
<script>
import * as API from '@/api/admin/wx-broadcast.js'
import TagsSelect from './components/TagsSelect.vue'
import MemberSelect from './components/MemberSelect'
import MaterialSelect from './components/MaterialSelect.vue'
import MaterialPreview from './components/MaterialPreview.vue'
export default {
  name: 'WxBroadCasting',
  components: { TagsSelect, MemberSelect, MaterialSelect, MaterialPreview },
  data: function () {
    return {
      tabIndex: 0,
      tableHeaders: [
        { text: 'id', value: 'id' },
        { text: '类型', value: 'type', width: 100 },
        { text: 'msgId', value: 'msg_id' },
        { text: 'mediaId', value: 'media_id' },
        { text: '接收者', value: 'touser' },
        // { text: '发送范围', value: 'scope' },
        { text: '状态', value: 'status' },
        { text: '时间', value: 'updatedAt' },
        { text: '操作', value: 'actions', align: 'center', width: 190 }
      ],
      tableLoading: true,
      tableItems: [],
      tableOptions: {
        page: 1,
        itemsPerPage: 20,
        sortBy: [ 'id' ],
        sortDesc: [ true ]
      },
      tableSearch: '',
      tableItemsTotal: 0,
      tablePageLength: 0,
      dialog: false,
      typeArray: [ 'artical', 'text', 'image', 'video', 'audio' ],
      typeArrayText: [ '文章', '文字', '图片', '视频', '音频' ],
      formData: {
        type: '',
        send_right_now: 0,
        scope: '',
        touser: null,
        media_id: ''
      },
      cover: '',
      btnLoading: false,
      previewMenu: false,
      previewAccount: ''
    }
  },
  created: function () {
    // this.fetchData()
  },
  computed: {
    type() {
      return this.typeArray[this.tabIndex]
    }
  },
  watch: {
    tableOptions: {
      handler () {
        this.fetchData()
      },
      deep: true
    }
  },
  methods: {
    fetchData() {
      this.tableLoading = true
      API.fetchList({
        sort: this.tableOptions.sortBy[0],
        descending: this.tableOptions.sortDesc[0],
        page: this.tableOptions.page,
        page_size: this.tableOptions.itemsPerPage,
        search: {}
      }).then(res => {
        this.tableItems = res.data.data
        this.tableItemsTotal = res.data.total
        this.tablePageLength = res.data.last_page
      }).finally(() => {
        this.tableLoading = false
      })
    },
    itemDeleteHandle(item) {
      if (confirm('是否确定删除？删除后无法恢复，请慎重！')) {
        API.deleteOne(item.id).then(res => {
          this.fetchData()
          this.$toasted.success(res.data)
        }).catch(err => {
          return Promise.reject(err)
        })
      }
    },
    itemSendHandle(item) {},
    // updateHandle() {},
    previewHandle({ mediaId, content }, type) {
      const p = mediaId || content
      if (!p) {
        this.$toasted.error('未选择内容！')
        this.previewMenu = false
        return false
      }
      if (!this.previewAccount) {
        this.$toasted.error('未输入微信号码内容！')
        return false
      }
      API.preview(p, this.previewAccount, type).then(res => {
        this.$toasted.success(res)
      }).finally(() => {
        this.previewMenu = false
      })
    },
    sumbitHandle() {
      this.$validator.validate().then(result => {
        if (result) {
          this.btnLoading = true
          this.formData.type = this.type
          API.createOne(this.formData).then(res => {
            this.dialog = false
            this.$refs.dialogForm.reset()
            this.formData = this.$options.data().formData
            this.$toasted.success(res.data)
            this.fetchData()
          }).finally(() => {
            this.btnLoading = false
          })
        }
      })
    }
  }
}
</script>
<style scoped>
</style>
